package com.liang.branchsearch;

public class BranchSearchForIndex {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int num = 10;

        //对数组arr进行查找，插入arr，num，返回值是index
        int index  = binarySearchForIndex(arr, num);
        System.out.println(index);
    }

    private static int binarySearchForIndex(int[] arr, int num) {
        //定义开始位置和结束位置
        int min = 0;
        int max = arr.length-1;

        //进行循环判断
        while (min <= max) {
            int mid = (min + max)/2;
            if (arr[mid] > num) {
                max = mid -1;
            } else if(arr[mid] < num){
                min = mid + 1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}
